package com.xr.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.xr.constant.MessageConstant;
import com.xr.constant.RedisMessageConstant;
import com.xr.pojo.Member;
import com.xr.result.Result;
import com.xr.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/*
* 处理会员相关操作
* */

@RestController
@RequestMapping("memberMobile")
public class MemberMobileController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody  Map map){
        String  telephone = (String)map.get("telephone");//手机号
        String codeInWeb =(String)map.get("validateCode");
        //从Redis中获取验证码
        String codeInRedis = jedisPool.getResource().get(telephone + "_"+RedisMessageConstant.SENDTYPE_LOGIN);
        System.out.println("redis:"+codeInRedis+"web:"+codeInWeb);
        if(codeInWeb!=null && codeInRedis != null && codeInRedis.equals(codeInWeb)){
            System.out.println("join ========>");
            //验证码输入正确
            //判断当前用户是否微会员
            Member member = memberService.queryByTelephone(telephone);
            if(member==null){
                //不是会员 则创建会员
                member.setRegtime(new Date());//创建日期
                member.setPhonenumber(telephone);//手机号
                memberService.insertMember(member);
            }
            //向客户端写入Cookie 内容为手机号
            Cookie cookie = new Cookie("member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);//设置有效期
            response.addCookie(cookie);
            //保存到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);//key 有效期 数据
            return  new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
            //验证码输入cuow
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
